using AutoMapper;
using B.S.NewMedical.Api.Read.Application.Command.MobileService.Consult;
using B.S.NewMedical.Api.Read.DTOS.Consult;
using B.S.NewMedical.Domain.Appointment;
using B.S.NewMedical.Domain.Doctor;
using B.S.NewMedical.Domain.Hospital;
using B.S.NewMedical.Domain.MobileService;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Read.Application.Handler.MobileService.Consult
{
    /// <summary>
    /// 获取健康咨询详情处理器
    /// </summary>
    public class GetConsultDetailHandler : IRequestHandler<GetConsultDetailCommand, ApiResult<ConsultDetailDto>>
    {
        private readonly IBaseRepository<ConsultQuestion> _questionRepository;
        private readonly IBaseRepository<ConsultAnswer> _answerRepository;
        private readonly IBaseRepository<ConsultCategory> _categoryRepository;
        private readonly IBaseRepository<B.S.NewMedical.Domain.Appointment.Doctor> _doctorRepository;
        private readonly IBaseRepository<HospitalModel> _hospitalRepository;
        private readonly IBaseRepository<DepartmentModel> _departmentRepository;
        private readonly IBaseRepository<HospitalDepartmentModel> _hospitalDepartmentRepository;
        private readonly ILogger<GetConsultDetailHandler> _logger;
        private readonly IMapper _mapper;

        public GetConsultDetailHandler(
            IBaseRepository<ConsultQuestion> questionRepository,
            IBaseRepository<ConsultAnswer> answerRepository,
            IBaseRepository<ConsultCategory> categoryRepository,
            IBaseRepository<B.S.NewMedical.Domain.Appointment.Doctor> doctorRepository,
            IBaseRepository<HospitalModel> hospitalRepository,
            IBaseRepository<DepartmentModel> departmentRepository,
            IBaseRepository<HospitalDepartmentModel> hospitalDepartmentRepository,
            ILogger<GetConsultDetailHandler> logger,
            IMapper mapper)
        {
            _questionRepository = questionRepository;
            _answerRepository = answerRepository;
            _categoryRepository = categoryRepository;
            _doctorRepository = doctorRepository;
            _hospitalRepository = hospitalRepository;
            _departmentRepository = departmentRepository;
            _hospitalDepartmentRepository = hospitalDepartmentRepository;
            _logger = logger;
            _mapper = mapper;
        }

        public async Task<ApiResult<ConsultDetailDto>> Handle(GetConsultDetailCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始获取健康咨询详情，问题ID：{QuestionId}", request.QuestionId);

                // 获取问题信息
                var question = await _questionRepository.GetAll()
                    .FirstOrDefaultAsync(q => q.Id == request.QuestionId && !q.IsDeleted, cancellationToken);

                if (question == null)
                {
                    return new ApiResult<ConsultDetailDto>
                    {
                        Code = ApiEnum.Error,
                        Msg = "问题不存在或已被删除"
                    };
                }

                // 获取分类信息
                var category = await _categoryRepository.GetAll()
                    .FirstOrDefaultAsync(c => c.Id == question.CatId && !c.IsDeleted, cancellationToken);

                // 获取问题下的所有回答
                var answers = await _answerRepository.GetAll()
                    .Where(a => a.QuestionId == request.QuestionId && !a.IsDeleted)
                    .OrderByDescending(a => a.LikeCnt)  // 点赞数多的排前面
                    .ToListAsync(cancellationToken);

                // 获取医生信息
                var doctorIds = answers.Select(a => a.DoctorId).Distinct().ToList();
                var doctors = await _doctorRepository.GetAll()
                    .Where(d => !d.IsDeleted && doctorIds.Contains(d.Id))
                    .ToListAsync(cancellationToken);
                
                // 获取所有涉及的科室ID
                var departmentIds = doctors.Select(d => d.Dept_id).Distinct().ToList();
                
                // 获取科室名称信息
                var departments = await _departmentRepository.GetAll()
                    .Where(d => !d.IsDeleted && departmentIds.Contains(d.Id))
                    .ToListAsync(cancellationToken);
                
                // 获取科室对应的医院关系
                var hospitalDepartments = await _hospitalDepartmentRepository.GetAll()
                    .Where(hd => !hd.IsDeleted && departmentIds.Contains(hd.DepartmentId))
                    .ToListAsync(cancellationToken);
                
                // 获取涉及的医院ID
                var hospitalIds = hospitalDepartments.Select(hd => hd.HospitalId).Distinct().ToList();
                
                // 获取医院信息
                var hospitals = await _hospitalRepository.GetAll()
                    .Where(h => !h.IsDeleted && hospitalIds.Contains(h.Id))
                    .ToListAsync(cancellationToken);
                
                // 创建科室ID到医院信息的映射
                var deptHospitalMap = new Dictionary<int, (string hospitalName, string departmentName)>();
                foreach (var dept in departmentIds)
                {
                    // 获取科室名称
                    var department = departments.FirstOrDefault(d => d.Id == dept);
                    string departmentName = department?.DepartmentName ?? "未知科室";
                    
                    // 获取科室对应的医院ID
                    var hospitalDept = hospitalDepartments.FirstOrDefault(hd => hd.DepartmentId == dept);
                    if (hospitalDept != null)
                    {
                        // 获取医院信息
                        var hospital = hospitals.FirstOrDefault(h => h.Id == hospitalDept.HospitalId);
                        if (hospital != null)
                        {
                            deptHospitalMap[dept] = (hospital.HospitalName ?? "未知医院", departmentName);
                            continue;
                        }
                    }
                    
                    // 默认值
                    deptHospitalMap[dept] = ("未知医院", departmentName);
                }

                // 构建问题DTO
                var questionDto = new ConsultQuestionDto
                {
                    Id = question.Id,
                    CatId = question.CatId,
                    CategoryName = category?.Name ?? "未知分类",
                    Title = question.Title,
                    Content = question.Content,
                    AuthorId = question.AuthorId,
                    AuthorName = "用户" + question.AuthorId, // 可能需要从用户表获取
                    LikeCnt = question.LikeCnt,
                    ViewCnt = question.ViewCnt,
                    Status = question.Status,
                    CreatedAt = question.CreatedAt,
                    Tags = "" // 可能需要从标签表获取
                };

                // 构建回答DTO列表
                var answerDtos = new List<ConsultAnswerDto>();
                foreach (var answer in answers)
                {
                    var doctor = doctors.FirstOrDefault(d => d.Id == answer.DoctorId);
                    
                    // 默认值
                    string hospitalName = "未知医院";
                    string departmentName = "未知科室";
                    
                    // 获取医院和科室信息
                    if (doctor != null && deptHospitalMap.ContainsKey(doctor.Dept_id))
                    {
                        var (hospital, department) = deptHospitalMap[doctor.Dept_id];
                        hospitalName = hospital;
                        departmentName = department;
                    }
                    
                    answerDtos.Add(new ConsultAnswerDto
                    {
                        Id = answer.Id,
                        QuestionId = answer.QuestionId,
                        Content = answer.Content,
                        DoctorId = answer.DoctorId,
                        DoctorName = doctor?.Doctor_name ?? "未知医生",
                        DoctorTitle = doctor?.JobTitle_id.ToString() ?? "",
                        Department = departmentName,
                        Hospital = hospitalName,
                        Avatar = doctor?.Photo ?? "",
                        LikeCnt = answer.LikeCnt,
                        CreatedAt = answer.CreatedAt
                    });
                }

                // 构建详情DTO
                var detailDto = new ConsultDetailDto
                {
                    Question = questionDto,
                    Answers = answerDtos
                };

                return new ApiResult<ConsultDetailDto>
                {
                    Code = ApiEnum.Success,
                    Msg = "获取健康咨询详情成功",
                    Data = detailDto
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取健康咨询详情时发生异常");
                return new ApiResult<ConsultDetailDto>
                {
                    Code = ApiEnum.Error,
                    Msg = "获取健康咨询详情失败：" + ex.Message
                };
            }
        }
    }
} 